import React, { useMemo } from 'react';
import { List } from 'antd';
import {
    DndContext,
    closestCenter,
    KeyboardSensor,
    PointerSensor,
    useSensor,
    useSensors,
    DragEndEvent,
} from '@dnd-kit/core';
import {
    // arrayMove,
    SortableContext,
    sortableKeyboardCoordinates,
    verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { restrictToVerticalAxis } from '@dnd-kit/modifiers';
import SortableItem from './SortableItem';
import { useListsStore, IFlattenedItem } from '../store/listStore';
import { flatten } from '../utils';
import genNewItems from './genNewItems';

// 导出一个默认的函数组件SortableList
export default function SortableList() {
  // 从useListsStore中获取items和setLists
  const items = useListsStore((state) => state.items)
  const setLists = useListsStore((state) => state.setLists)
  // 使用useMemo将items扁平化
  const flattenedLists = useMemo(
    () => flatten(items as IFlattenedItem[]),
    [items]
  )

  // 使用useSensors获取PointerSensor和KeyboardSensor
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  )

  // 处理拖拽结束事件
  function handleDragEnd(event: DragEndEvent) {
    const { active, over } = event
    if (over == null) return
    if (active.id === over.id) return

    // 获取over的祖先id
    const { ancestorIds: overAncestorIds = [] } = over.data.current || {}
    if (overAncestorIds.includes(active.id)) {
      return
    }
    // 生成新的items
    const newItems = genNewItems(
      items,
      flattenedLists,
      active.id.toString(),
      over.id.toString()
    )
    // 设置新的items
    setLists(newItems)
  }

  // 如果flattenedLists为空，则返回null
  if (flattenedLists.length === 0) return null

  // 返回DndContext组件
  return (
    <DndContext
      sensors={sensors}
      collisionDetection={closestCenter}
      onDragEnd={handleDragEnd}
      modifiers={[restrictToVerticalAxis]}
    >
      <SortableContext
        items={flattenedLists}
        strategy={verticalListSortingStrategy}
      >
        <List 
            itemLayout="horizontal"
            dataSource={flattenedLists}
            renderItem={(item, index) =>(
                <SortableItem key={item.id} item={item} />
            )}
        />
      </SortableContext>
    </DndContext>
  )
}
